package com.example.myapplication

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.graphics.ImageFormat
import android.graphics.SurfaceTexture
import android.hardware.camera2.CameraCaptureSession
import android.hardware.camera2.CameraDevice
import android.hardware.camera2.CameraManager
import android.hardware.camera2.CaptureRequest
import android.media.ImageReader
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.Surface
import android.view.TextureView
import android.widget.Button
import android.widget.ImageView
import androidx.core.app.ActivityCompat

class   MainActivity : AppCompatActivity() {
    lateinit var camera_device : CameraDevice
    lateinit var texture_view_surface: Surface
    lateinit var image_reader_surface:Surface
    lateinit var capture_session: CameraCaptureSession
    lateinit var image_reader: ImageReader
    lateinit var image_view: ImageView
    lateinit var capture_callback:CameraCaptureSession.CaptureCallback


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        image_view = findViewById(R.id.imageView)

        val texture_view = findViewById<TextureView>(R.id.textureView)
        texture_view.surfaceTextureListener =
            object : TextureView.SurfaceTextureListener {
                override fun onSurfaceTextureAvailable(
                    surface: SurfaceTexture,
                    width: Int,
                    height: Int
                ) {
                    texture_view_surface = Surface(texture_view.surfaceTexture)
                    open_camera()
                }

                override fun onSurfaceTextureSizeChanged(
                    surface: SurfaceTexture,
                    width: Int,
                    height: Int
                ) {
                }

                override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
                    return false
                }

                override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
                }

            }
        val take_photo_button = findViewById<Button>(R.id.button)
        take_photo_button.setOnClickListener {
            take_photo()
        }

    }

    fun take_photo() {
        val request_builder = camera_device.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE)
        request_builder.addTarget(image_reader_surface)
        request_builder.set(CaptureRequest.JPEG_ORIENTATION,90)

        val request = request_builder.build()

        capture_session.capture(request, null,null)

    }




    val image_available = ImageReader.OnImageAvailableListener {
        Log.i("bieber","got a image")
        val image = it.acquireLatestImage()
        val buffer = image.planes[0].buffer
        val bytes_n = buffer.remaining()

        var bytes = ByteArray(bytes_n)
        buffer.get(bytes)

        image.close()

        val bitmap = BitmapFactory.decodeByteArray(bytes,0,bytes_n)

        image_view.setImageBitmap(bitmap)


    }

    fun open_camera() {
        image_reader = ImageReader.newInstance(200,200,ImageFormat.JPEG,2)
        image_reader_surface = image_reader.surface
        image_reader.setOnImageAvailableListener(image_available,null)

        val camera_manager = getSystemService(
            Context.CAMERA_SERVICE
        ) as CameraManager

        requestPermissions(arrayOf(Manifest.permission.CAMERA),11)

        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            return
        }
        camera_manager.openCamera(camera_manager.cameraIdList[0],
            camera_state_callback,null)

        val characteristics = camera_manager.getCameraCharacteristics(camera_manager.cameraIdList[0])




    }

    val camera_state_callback =
        object : CameraDevice.StateCallback() {
            override fun onOpened(camera: CameraDevice) {
                camera_device = camera

                camera_device.createCaptureSession(
                    listOf(image_reader_surface,texture_view_surface),
                    session_state_callback,
                    null
                )
            }

            override fun onDisconnected(camera: CameraDevice) {
            }

            override fun onError(camera: CameraDevice, error: Int) {
            }

        }
    val session_state_callback =
        object : CameraCaptureSession.StateCallback() {
            override fun onConfigured(session: CameraCaptureSession) {
                capture_session = session

                val request_builder = camera_device.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
                request_builder.addTarget(texture_view_surface)

                val request = request_builder.build()
                request.get(CaptureRequest.CONTROL_CAPTURE_INTENT)
                capture_session.setRepeatingRequest(request,null,null)
            }

            override fun onConfigureFailed(session: CameraCaptureSession) {

            }

        }

}